<?php
require_once("libs/Mijireh/Mijireh.php");
@session_start();
class Checkout extends Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
//        echo URL;exit;
        $sql = new sql();
        $sql->connect();
        $serverreply = "";
		$paymentArray = $_SESSION['paymentArray'];
		if(count($_SESSION['shoping_cart']) == 0){
			header("Location: " . URL . "product");
		}
		
		$errorArray = Array();
		//$this->view->ErrorMessage = '';
		
		$salutation = '';
		$fname = '';
		$lname = '';
		$email = '';
		$zipcode = '';
		$address = '';
		$state = '';
		$city = '';
		$phone = '';
		$country = '';
		
        if (@$_POST['continue']) {
            
			
			function ValidEmailAddress($EmailAddress) {
				if (!preg_match("/^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i", $EmailAddress)) {
					return false;
				}
				return true;
			}
	
	
			$salutation = $_POST['salutation'];
			$fname = $_POST['fname'];
			$lname = $_POST['lname'];
			$email = $_POST['email'];
			$zipcode = $_POST['zipcode'];
			$address = $_POST['address'];
			$state = $_POST['state'];
			$city = $_POST['city'];
			$phone = $_POST['phone'];
			$country = $_POST['country'];
		
			if ( trim($_POST['salutation']) == "" ) {
				$errorArray[] = 'Please select salutation';
			}
			
			if ( trim($_POST['fname']) == "" ) {
				$errorArray[] = 'Please enter firstname';
			}
			
			if ( trim($_POST['lname']) == "" ) {
				$errorArray[] = 'Please enter lastname';
			}
			
			if ( trim($_POST['email']) == "" ) {
				$errorArray[] = 'Please enter email';
			}
			
			if ( !ValidEmailAddress($_POST['email'])) {
				$errorArray[] = 'Please enter valid email';
			}
			
			if ( trim($_POST['zipcode']) == "" ) {
				$errorArray[] = 'Please enter zipcode';
			}
			
			if ( trim($_POST['address']) == "" ) {
				$errorArray[] = 'Please enter address';
			}
			
			if ( trim($_POST['state']) == "" ) {
				$errorArray[] = 'Please enter state';
			}
			
			if ( trim($_POST['city']) == "" ) {
				$errorArray[] = 'Please enter city';
			}
			
			if ( trim($_POST['phone']) == "" ) {
				$errorArray[] = 'Please enter phone no.';
			}
			
			if ( trim($_POST['country']) == "" ) {
				$errorArray[] = 'Please select country';
			}
			
			
			
			
			if(count($errorArray) > 0){
			
			}
			else{
						$total_Amount = 0;
				 foreach($_SESSION['shoping_cart'] as $key => $value){
					$total_Amount += $value['prd_qty']*$value['prd_price'];
				}
			
			
				$UserArray = $sql->fetch("tbl_user", array("user_email" => $_POST['email']));
				if($UserArray['user_id'] != ''){
				   // echo 'in';exit;
					$lastid = $UserArray['user_id'];
				}
				else{
					 $arraydata = array("user_prefix" => $_POST['salutation'],
						"user_firstname" => $_POST['fname'],
						"user_lastname" => $_POST['lname'],
						"user_email" => $_POST['email'],
						"user_zipcode" => $_POST['zipcode'],
						"user_address" => $_POST['address'],
						"user_state" => $_POST['state'],
						"user_city" => $_POST['city'],
						"user_phoneno" => $_POST['phone'],
						"user_country" => $_POST['country'],
						"user_createdate" => date('Y-m-d h:i:s'),
						"user_status" => 1,
					);
					$insert = $sql->insert('tbl_user', $arraydata);
					$lastid = $sql->last_id();
					
					
					include('quickbooks/add_customer.php');
					$last_quickbook_id = $resp;
					$updatedata = array(
							"quick_book_id" => $last_quickbook_id,
					);
					$update = $sql->update('tbl_user', $updatedata, array("user_id" => $lastid));
					
				}	
					//Mijireh Store 1
				$mij_access_key = "";
				$pt_type = "";
				
				
				foreach($paymentArray as $p_key =>$p_value){
                    if ($_POST['payment_optn'] == $p_key) {
                        $mij_access_key = $p_value['mij_access_key'];
                        $pt_type = $p_value['Name'];
                    }
                }
				
				/*if($_POST['payment_optn'] == '1'){
					$mij_access_key = 'f09c94c68b4ca4181451a7f5';
					$pt_type = 'CHARGE';
				}else if($_POST['payment_optn'] == '2'){
					$mij_access_key = 'd16fbe7d760d70650ca8246b';
					$pt_type = 'GPRO';
				}*/
				
				// Mijireh Payment
				Mijireh::$access_key = $mij_access_key;//244ec644addfa238a4602d58';//<your_mijireh_store_access_key>;
				// get store info
				$store_info = Mijireh::get_store_info();
				$address = new Mijireh_Address();
				$address->street = $_POST['address'];
				$address->city = $_POST['city'];
				$address->state_province = $_POST['state'];
				$address->zip_code = $_POST['zipcode'];
				$address->country = $_POST['country'];
				$address->phone = $_POST['phone'];
				$address->first_name = $_POST['fname'];
				$address->last_name = $_POST['lname'];
				$order = new Mijireh_Order();
				$order->set_shipping_address($address);
				$order->set_billing_address($address);
				$order->add_email_detail($_POST['email']);
				foreach($_SESSION['shoping_cart'] as $key => $value){
					$price = $value['prd_qty'] * $value['prd_price'];
					$order->add_item($value['prd_name'], $value['prd_price'], $value['prd_qty'], 'product'.$key);
				}
				
				
				$order->return_url = URL . "thankyou/".$lastid."/".trim($_POST['payment_optn']);
				//'http://localhost/kanijfatma/payment_gateway/mijireh/thankyou.php';
				$order->shipping = 0.00;
				$order->tax = 0.00;
				$order->discount = 0.00;
				$order->total = $total_Amount; // sum of items + shipping + tax - discount
				$order->create();
				header('Location: ' . $order->checkout_url);
			  
			}
		
    }		
		
		//Fetch the Current Key
		$keyArray = $sql->fetch("tbl_metadata", array("mtd_key" => 'payment_key'));
		$key = $keyArray['mtd_value'];	
        
		$updatedPaymentArray = array();
		foreach($paymentArray as $p_key =>$p_value){
           $updatedPaymentArray[$p_key] = $p_value['Name'];
		}
	   
	   
		/*$updatedPaymentArray  = array(
            '1' => 'CHARGE',
            '2' => 'GPRO'
        );*/
        
		for($i=$key+1; $i<=count($paymentArray); $i++) {
			$paymentstore[$i] = $updatedPaymentArray[$i];
		}

		for($j=1; $j<=$key; $j++) {
			$paymentstore[$j] = $updatedPaymentArray[$j];
		}
		
	
		$this->view->salutation = $salutation;
		$this->view->fname = $fname;
		$this->view->lname = $lname;
		$this->view->email = $email;
		$this->view->zipcode = $zipcode;
		$this->view->address = $address;
		$this->view->state = $state;
		$this->view->city = $city;
		$this->view->phone = $phone;
		$this->view->country = $country;
		
        $this->view->ErrorMessage = $errorArray;
        $this->view->paymentstore = $paymentstore;
        $this->view->render('checkout');

		
}
}

